import React, { useEffect, useState } from 'react'
import { NavBar } from 'react-vant';
import { useLocation, useNavigate } from 'react-router-dom';
import { Dropdown } from 'antd-mobile'
import axios from 'axios';
import { ProductCard, Tag } from 'react-vant';
import style from './index.module.scss';
import { SideBar } from 'antd-mobile'
import { tabs } from './tabs'
import classNames from 'classnames'
const Index: React.FC = () => {
    const [activeKey, setActiveKey] = useState('key1')
    const [active, setActive] = useState(0);
    const navigate = useNavigate();
    const [list, setlist] = useState([]);
    const [dizhitext, setDizhiText] = useState(localStorage.getItem('dizhitext') || '');
    // 当前页码，初始为1
    const [currentPage, setCurrentPage] = useState(1);
    // 每页显示的数据数量，可根据实际情况调整
    const PAGE_SIZE = 10;
    // 用于标记是否正在加载数据，避免重复请求
    const [isLoading, setIsLoading] = useState(false);
    // 用于判断是否滚动到底部的阈值（单位为像素，这里设为200，可按需调整）
    const threshold = 200;
    useEffect(() => {
        const fetchInitialData = async () => {
            try {
                setIsLoading(true);
                const res = await axios.get('/api/date', {
                    params: {
                        currentPage: 1,
                        pageSize: PAGE_SIZE
                    }
                });
                setlist(res.data.data);
                setIsLoading(false);
            } catch (error) {
                console.error('获取初始数据出错:', error);
                setIsLoading(false);
            }
        };

        fetchInitialData();
    }, [])
    // 用于获取更多数据（模拟下拉刷新的加载新数据操作）的函数
    const fetchMoreData = async () => {
        if (isLoading) {
            return;
        }
        setIsLoading(true);
        try {
            const nextPage = currentPage + 1;
            const res = await axios.get('/api/date', {
                params: {
                    currentPage: nextPage,
                    pageSize: PAGE_SIZE
                }
            });
            // 将新获取的数据合并到原列表数据中
            setlist(prevList => [...prevList, ...res.data.data]);
            setCurrentPage(nextPage);
        } catch (error) {
            console.error('获取更多数据出错:', error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        const handleScroll = () => {
            // 获取页面滚动高度
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            // 获取可视区域高度
            const windowHeight = document.documentElement.clientHeight;
            // 获取整个文档高度
            const documentHeight = document.documentElement.scrollHeight;
            // 判断是否滚动到底部（考虑阈值），如果是则调用获取更多数据的函数
            if (scrollTop + windowHeight + threshold >= documentHeight && !isLoading) {
                fetchMoreData();
            }
        };

        window.addEventListener('scroll', handleScroll);

        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, [isLoading]);


    const dizhi = [
        {
            text: '北京',
            value: '1'
        },
        {
            text: '上海',
            value: '2'
        },
        {
            text: '广州',
            value: '3'
        },
        {
            text: '深圳',
            value: '4'
        },
        {
            text: '杭州',
            value: '5'
        },
        {
            text: '成都',
            value: '6'
        },
        {
            text: '重庆',
            value: '7'
        },
        {
            text: '武汉',
            value: '8'
        },
        {
            text: '南京',
            value: '9'
        },
        {
            text: '西安',
            value: '10'
        },
    ]
    const nei = [
        {
            'to': '华北地区',
            "list": [
                {
                    text: '北京',
                    value: '1'
                },
                {
                    text: '天津',
                    value: '2'
                },
                {
                    text: '河北',
                    value: '3'
                },
                {
                    text: '山西',
                    value: '4'
                },
                {
                    text: '内蒙古',
                    value: '5'
                }
            ]
        },
        {
            'to': '华东地区',
            "list": [
                {
                    text: '上海',
                    value: '1'
                },
                {
                    text: '江苏',
                    value: '2'
                },
                {
                    text: '浙江',
                    value: '3'
                },
                {
                    text: '安徽',
                    value: '4'
                },
                {
                    text: '福建',
                    value: '5'
                }
            ]
        },
        {
            'to': '华西地区',
            "list": [
                {
                    text: '四川',
                    value: '1'
                },
                {
                    text: '重庆',
                    value: '2'
                },
                {
                    text: '贵州',
                    value: '3'
                },
                {
                    text: '云南',
                    value: '4'
                },
                {
                    text: '西藏',
                    value: '5'
                }
            ]
        },
        {
            'to': '华南地区',
            "list": [
                {
                    text: '广西',
                    value: '1'
                },
                {
                    text: '海南',
                    value: '2'
                },
                {
                    text: '香港',
                    value: '3'
                },
                {
                    text: '澳门',
                    value: '4'
                },
                {
                    text: '广东',
                    value: '5'
                }
            ]
        },
    ]

    const dianji = (item: string) => {
        console.log(item);
        navigate(0)
        localStorage.setItem('dizhitext', item)
    }
    const fgh=()=>{
        navigate(0)
    }
    const xiangqing = (item: any) => {
        // console.log(item);
        navigate('/xiangqing', {
            state: {
                item
            }
        })
    }

    const [sortBy, setSortBy] = useState('');
    const fetchMoreData1 = async () => {
        if (isLoading) {
            return;
        }
        setIsLoading(true);
        try {
            const nextPage = currentPage + 1;
            const res = await axios.get('/api/date', {
                params: {
                    currentPage: nextPage,
                    pageSize: PAGE_SIZE
                }
            });

            let newList = [...list, ...res.data.data];
            if (sortBy === "asc") {
                // 从低到高排序（按照价格升序）
                newList = newList.sort((a, b) => a.tongh - b.tongh);
            } else if (sortBy === "desc") {
                // 从高到低排序（按照价格降序）
                newList = newList.sort((a, b) => b.tongh - a.tongh);
            }
            setlist(newList);
            setCurrentPage(nextPage);
        } catch (error) {
            console.error('获取更多数据出错:', error);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className={style.box}>
            <div className={style.fff}>
                <NavBar
                    title="私人医生"
                    leftText="返回"
                    rightText="服务承诺"
                    onClickLeft={() => navigate(-1)}
                />
                <Dropdown>
                    <Dropdown.Item key='sorter' title={
                        dizhitext ? dizhitext : '未定位'
                    }>
                        <div style={{ padding: 12 }}>
                            <div className={style.shang}>
                                <h5>当前定位地区</h5>
                                <div>{
                                    dizhitext ? dizhitext : '未定位'
                                }</div>
                            </div>
                            <div className={style.okok}>
                                <h5>重点城市</h5>
                                {
                                    dizhi.map((item: any, index: any) => {
                                        return <div className={style.okok1} key={index} onClick={() => dianji(item.text)}>{item.text}</div>
                                    })
                                }
                            </div>
                            <div className={style.xiaaaa}>
                                {
                                    nei.map((item: any, index: any) => {
                                        return <div key={index}>
                                            <h5>{item.to}</h5>
                                            {
                                                item.list.map((item1: any, index1: any) => {
                                                    return <div key={index1}>{item1.text}</div>
                                                })
                                            }
                                        </div>
                                    })
                                }
                            </div>
                        </div>
                    </Dropdown.Item>
                    <Dropdown.Item key='bizop' title='商机筛选'>
                        <div className={style.container}>
                            <div className={style.side}>
                                <SideBar activeKey={activeKey} onChange={setActiveKey}>
                                    {tabs.map(item => (
                                        <SideBar.Item key={item.key} title={item.title} />
                                    ))}
                                </SideBar>
                            </div>
                            <div className={style.main}>
                                {
                                    tabs.map(item => (
                                        <div
                                            key={item.key}
                                            className={classNames(
                                                style.content,
                                                activeKey === item.key && style.active
                                            )}
                                        >
                                            {item.title}
                                            {
                                                item.children.map((item1: any, index: any) => {
                                                    return <p key={index} onClick={fgh}>{item1.name}</p>
                                                })
                                            }
                                        </div>
                                    ))
                                }
                            </div>
                        </div>
                    </Dropdown.Item>
                    <Dropdown.Item key='more' title='价格排序' onClick={() => { fetchMoreData1(),setCurrentPage(1); }}>
                        <div style={{ padding: 12 }}>
                            <p onClick={() => setSortBy('')}>综合排序</p>
                            <br />
                            <p onClick={() => setSortBy('desc')}>价格由高到低</p>
                            <br />
                            <p onClick={() => setSortBy('asc')}>价格由低到高</p>
                        </div>
                    </Dropdown.Item>

                </Dropdown>
            </div>
            <div className={style.shuju}>
                {
                    list.map((item: any, index: any) => {
                        return <ProductCard key={index}
                            onClick={() => xiangqing(item)}
                            num="1"
                            price={item.tongh}
                            desc={item.shanc}
                            title={item.name}
                            thumb={item.image}
                            tags={
                                <>
                                    <Tag plain type="danger" style={{ marginRight: 5 }}>
                                        {item.sex}
                                    </Tag>
                                    <Tag plain type="danger">
                                        {item.type}
                                    </Tag>
                                </>
                            }
                            footer={
                                <>
                                    <p>地址：{item.address}</p>
                                    <p>专职：{item.keshi}</p>
                                </>
                            }
                        />
                    })

                }
                {isLoading && <div>正在加载更多...</div>}
            </div>
        </div>
    )
}

export default Index
